이미지의 가장자리 경계면 검출 (edge detection) 원리와 예제

 2차원 이미지의 경계면을 찾는 원리는 다음과 같다. 

 


이미지의 경계면은 보통 위 그림의 a와 같이 색의 차이가 있는 것을 볼 수 있으며, 1차원으로 보면 그림의 b처럼 나타낼 수 있다. 이 색의 차이가 많아지는 부분은 미분을 통해(그림의 c) 찾을 수 있다.


미분연산은 합성곱(convolution) 연산을 사용하여 근사치를 계산할 수 있다.

예를 들어 아래와 같이 2개의 gx, gy matrix를 사용해 2d 이미지에서 미분 값이 큰 위치를 찾을 수 있다. 즉 이미지의 경계면을 찾을 수 있다. 

def main():
    gx = np.array([(-1,0,1),
                   (-2,0,2),
                   (-1,0,1)])
    gy = np.array([(-1,-2,1),
                   (0,0,0),
                   (1,2,1)])

    src = np.array([(125,255,255,255,255,255),
                    (000,125,255,255,255,255),
                    (000,000,125,255,255,255),
                    (000,000,000,125,255,255),
                    (000,000,000,000,125,255),
                    (000,000,000,000,000,125)])
    
    x = np.abs(convolve2D(src,gx))
    y = np.abs(convolve2D(src,gy))
    print(x+y)


[[1530. 1030.  510.  510.]

 [1010. 1530. 1030.  510.]

 [ 250. 1010. 1530. 1030.]

 [   0.  250. 1010. 1530.]]


Opencv에서는 이미지 경계면을 찾는 방법들을 제공한다. 

import cv2 as cv

def Sobel(src):
#https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d
    Gx = cv.Sobel(src, cv.CV_16S, 1, 0,ksize=3)
    Gy = cv.Sobel(src, cv.CV_16S, 0, 1,ksize=3)
    edge = cv.addWeighted(cv.convertScaleAbs(Gx), 0.5, cv.convertScaleAbs(Gy), 0.5, 0)
    cv.imshow('SobelDerivatives',edge)

def Laplace(src):
    #https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#gad78703e4c8fe703d479c1860d76429e6
    edge = cv.Laplacian(src, cv.CV_16S, ksize=3)
    edge = cv.convertScaleAbs(edge)
    cv.imshow('Laplace',edge)
    
def Canny(src):
    #https://docs.opencv.org/master/dd/d1a/group__imgproc__feature.html#ga2a671611e104c093843d7b7fc46d24af
    edge = cv.Canny(src, 0, 50)
    mask = edge != 0
    dst = src * (mask[:,:].astype(src.dtype))
    cv.imshow('Canny', dst)

def edge_detection():
    img = cv.imread(32683062431.jpg')
    cv.imshow('img',img)
    gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    
    Sobel(gray)
    Laplace(gray)
    Canny(gray)

    cv.waitKey(0)
    cv.destroyAllWindows()


 



Sobel Derivatives https://docs.opencv.org/master/d2/d2c/tutorial_sobel_derivatives.html
Laplace Operator https://docs.opencv.org/master/d5/db5/tutorial_laplace_operator.html
Canny Edge Detector https://docs.opencv.org/master/da/d5c/tutorial_canny_detector.html


댓글

댓글 쓰기